namespace ScrumSprintMonitor.UI.Wpf.Avatars
{
	#region #using Directives

	using System;
	using System.ComponentModel.Composition;
	using System.Security.Cryptography;
	using System.Text;

	using Infrastructure;

	#endregion

	[Export(typeof(IAvatarProvider))]
	internal class GravatarAvatarProvider : IAvatarProvider
	{
		#region IAvatarProvider Members

		public string ProviderId
		{
			get { return "gravatar.com"; }
		}

		public IAvatar GetAvatar(string avatarKey)
		{
			var uri = new Uri(string.Format("http://www.gravatar.com/avatar/{0}.jpg", GetMd5Hash(avatarKey)), UriKind.Absolute);

			return new WpfUriAvatar(uri);
		}

		#endregion

		private static string GetMd5Hash(string input)
		{
			// Create a new instance of the MD5CryptoServiceProvider object.   
			var md5Hasher = MD5.Create();

			// Convert the input string to a byte array and compute the hash.   
			var data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));

			// Create a new Stringbuilder to collect the bytes   
			// and create a string.   
			var sBuilder = new StringBuilder();

			// Loop through each byte of the hashed data   
			// and format each one as a hexadecimal string.   
			foreach (byte t in data)
			{
				sBuilder.Append(t.ToString("x2"));
			}

			return sBuilder.ToString(); // Return the hexadecimal string.   
		}
	}
}